﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Controls;

namespace ChineseChess.Game.AI
{
    public class Ai8:BaseAi
    {
        /// <summary>
        /// Ai的算法
        /// </summary>
        /// <param name="pieceList">当前局面</param>
        /// <param name="canvas"></param>
        /// <param name="deep">计算深度</param>
        public static void Run(List<Piece> pieceList, Canvas canvas, int deep = 4)
        {
            List<Piece> pies = pieceList;
            initTable();
            int alpha = 99999;
            int beta = -99999;
            Moves mv = Search(deep, pies,alpha,beta, false);

            Piece p = clearPiece(pieceList, (int)mv.p.X, (int)mv.p.Y);//吃掉子
            //MessageBox.Show(mv.pie.Name.ToString() + mv.pie.X + "," + mv.pie.Y + ", " + mv.p.ToString());
            if (p != null)
            {
                canvas.Children.Remove(p);
            }

            for (int i = 0; i < pieceList.Count; i++)
            {
                var pie = pieceList[i];
                if (pie.X == mv.pie.X && pie.Y == mv.pie.Y)
                {
                    pie.X = (int)mv.p.X;
                    pie.Y = (int)mv.p.Y;
                    pie.InvalidateVisual();
                }
            }
        }

        private static Moves Search(int deep, List<Piece> pies, int alpha, int beta, bool isred)
        {
            if (deep <= 0)
            {
                Moves result = new Moves();
                result.score = evaluate(pies, isred);
                return result;
            }

            int bestid = 0;
            int score;
            var moves = generateMoves(pies, isred);

            for (int i = 0; i < moves.Count; i++)
            {
                var mv = moves[i];

                Moves historyMv = null;
                Piece eatedPie = MovePie(pies, mv, out historyMv);
                
                score = - Search(deep - 1, pies, -beta, -alpha, !isred).score;

                BackMovePie(pies, eatedPie, historyMv);
                
                if (score >= alpha)
                {
                    bestid = i;
                    alpha = score;
                }
                if (alpha >= beta)
                {   //剪枝
                    break;
                } 
            }
            Moves res = moves[bestid];
            res.score = alpha;
            return res;
        }
    }
}
